<template>
<!--  <div class="modal-overlay">-->
  <div class="virtual-param-dialog modal-main" :style="{ left: position.x + 'px', top: position.y + 'px' }">
    <div class="dialog-header modal-header" @mousedown="startDrag" :style="{ cursor: isDragging ? 'grabbing' : 'grab' }">
      <h2>虚拟参数管理</h2>
      <button class="close-btn" @click="$emit('close')">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>
    </div>
    
    <div class="dialog-content">
      <!-- 左侧参数列表 -->
      <div class="left-panel">
        <h3 class="panel-title">当前回放文件参数</h3>
        <!-- <div class="file-selector">
          <label class="file-label">选择文件：</label>
          <select v-model="selectedFile" @change="onFileChange" class="tech-select">
            <option v-for="file in availableFiles" :key="file.name" :value="file.name">
              {{ file.name }}
            </option>
          </select>
        </div> -->
        <div class="search-box flex gap-2">
          <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索参数..."
            class="tech-input"
          />
        </div>
        <div class="param-list">
          <div
            v-for="param in flatParameters"
            :key="param.name"
            class="param-item"
            @dblclick="addParamToFormula(param)"
          >
            <span class="param-name">{{ param.name }}</span>
          </div>
        </div>
      </div>
      
      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 已创建的虚拟参数列表 -->
        <div class="virtual-param-list">
          <div class="param-list-header">
            <h3 class="panel-title" style="padding-top: 0">已创建虚拟参数</h3>
            <div class="batch-actions">
              <button
                class="tech-btn"
                @click="drawSelectedParams"
              >
                绘制参数 ({{ selectedParams.length }})
              </button>
            </div>
          </div>
          <div class="virtual-table">
            <div class="table-header">
              <span>选择</span>
              <span>类型</span>
              <span>名称</span>
              <span>操作</span>
            </div>
            <div class="table-body">
              <div
                v-for="vParam in virtualParameters"
                :key="vParam.id"
                class="table-row"
              >
                <lable class="checkbox-wrapper">
                  <input
                    type="checkbox"
                    :id="`param-${vParam.id}`"
                    v-model="selectedParams"
                    :value="vParam.name"
                    class="param-checkbox"
                  />
                </lable>
                <span class="param-type-badge" :class="vParam.type == 0 ? 'param-type-badge_formula' : 'param-type-badge_calibration'">
                  {{ vParam.type == 0 ? '自建公式' : '标定线转换' }}
                </span>
                <span class="param-name-table">{{ vParam.name }}</span>
                <div class="actions">
                  <button
                    class="action-btn tech-btn"
                    :class="{ 'tech-btn-active': editingParam && editingParam.id === vParam.id }"
                    @click="editVirtualParam(vParam)"
                  >
                    {{ editingParam && editingParam.id === vParam.id ? '取消' : '编辑' }}
                  </button>
                  <button class="action-btn tech-btn-warn" @click="deleteVirtualParam(vParam)">
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 虚拟参数编辑区 -->
        <div class="edit-area">
          <div class="tab-header">
            <button
              class="tab-btn"
              :class="{ active: activeTab === 'formula' }"
              @click="activeTab = 'formula'"
            >
              自建公式
            </button>
            <button
              class="tab-btn"
              :class="{ active: activeTab === 'calibration' }"
              @click="activeTab = 'calibration'"
            >
              标定线转换
            </button>
          </div>
          
          <!-- 自建公式标签页 -->
          <div v-if="activeTab === 'formula'" class="formula-tab">
            <div class="formula-display">
              <div class="formula-input">{{ formulaExpression }}</div>
              <div class="formula-note">平方根及绝对值运算需要补全括号</div>
              <div class="calculator">
                <div class="calc-row">
                  <button class="tech-btn" @click="addToFormula('(')">(</button>
                  <button class="tech-btn" @click="addToFormula(')')">)</button>
                  <button class="calc-btn tech-btn operator" @click="clearFormula()">清空</button>
                  <button class="calc-btn tech-btn operator" @click="backspaceFormula()">←</button>
                </div>
                <div class="calc-row">
                  <button class="tech-btn" @click="addToFormula('7')">7</button>
                  <button class="tech-btn" @click="addToFormula('8')">8</button>
                  <button class="tech-btn" @click="addToFormula('9')">9</button>
                  <button class="calc-btn tech-btn operator" @click="addToFormula('/')">/</button>
                </div>
                <div class="calc-row">
                  <button class="tech-btn" @click="addToFormula('4')">4</button>
                  <button class="tech-btn" @click="addToFormula('5')">5</button>
                  <button class="tech-btn" @click="addToFormula('6')">6</button>
                  <button class="calc-btn tech-btn operator" @click="addToFormula('*')">×</button>
                </div>
                <div class="calc-row">
                  <button class="tech-btn" @click="addToFormula('1')">1</button>
                  <button class="tech-btn" @click="addToFormula('2')">2</button>
                  <button class="tech-btn" @click="addToFormula('3')">3</button>
                  <button class="calc-btn tech-btn operator" @click="addToFormula('-')">-</button>
                </div>
                <div class="calc-row">
                  <button class="tech-btn calc-btn-wide" @click="addToFormula('0')">0</button>
                  <button class="calc-btn tech-btn operator" @click="addToFormula('+')">+</button>
                </div>
                <div class="calc-row">
                  <button class="tech-btn" @click="addToFormula('.')">.</button>
                  <button class="calc-btn tech-btn function" @click="addToFormula('^')">^</button>
                  <button class="calc-btn tech-btn function" @click="addToFormula('sqrt(')">√</button>
                  <button class="calc-btn tech-btn function" @click="addToFormula('abs(')">|x|</button>
                </div>
              </div>
            </div>
            <div class="formula-name">
              <!-- <label>虚拟参数名称：</label> -->
              <input
                v-model="formulaName"
                type="text"
                placeholder="输入虚拟参数名称"
                class="name-input"
              />
              <button class="save-btn tech-btn" @click="saveFormula" :disabled="!formulaName || !formulaExpression || isLoading">
                {{ isLoading ? '保存中...' : '保存' }}
              </button>
            </div>
          </div>
          
          <!-- 标定线转换标签页 -->
          <div v-if="activeTab === 'calibration'" class="calibration-tab">
            <div class="calibration-form">
              <div class="form-group">
                <label>选择参数：</label>
                <input
                  v-model="calibrationParamName"
                  type="text"
                  placeholder="从左侧列表双击选择参数"
                  class="calibration-input"
                  readonly
                />
              </div>
              
              <div class="form-group">
                <label>X轴标定点：</label>
                <input
                  v-model="xCalibrationPoints"
                  type="text"
                  placeholder="输入X轴标定点，用英文逗号分隔"
                  class="calibration-input"
                  @input="handleXCalibrationInput"
                />
              </div>
              
              <div class="form-group">
                <label>Y轴标定点：</label>
                <input
                  v-model="yCalibrationPoints"
                  type="text"
                  placeholder="输入Y轴标定点，用英文逗号分隔"
                  class="calibration-input"
                  @input="handleYCalibrationInput"
                />
              </div>
              
              <div class="form-group">
                <label class="tech-checkbox">
                  <input
                    v-model="allowExtrapolation"
                    type="checkbox"
                    class="form-checkbox"
                  />
                  <span class="checkbox-custom"></span>
                  <span>允许外插</span>
                </label>
              </div>
              
              <div class="form-group">
                <label>虚拟参数名称：</label>
                <input
                  v-model="virtualName"
                  type="text"
                  placeholder="输入虚拟参数名称"
                  class="name-input"
                />
              </div>
              
              <button
                class="save-btn tech-btn"
                @click="saveCalibration"
                :disabled="!virtualName || !calibrationParamName || !xCalibrationPoints || !yCalibrationPoints || isLoading"
              >
                {{ isLoading ? '保存中...' : '保存' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Loading遮罩层 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="spinner"></div>
    </div>
  </div>
  <!-- 消息提示组件 -->
  <Message ref="messageRef" />
<!--  </div>-->
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import type { Parameter } from '../../types'
import API from './virtualParameter.api'
import Message from '@/components/BaseComponents/Message.vue';

// 消息提示组件引用
const messageRef = ref<InstanceType<typeof Message> | null>(null);
interface VirtualParameter {
  id?: number
  name: string
  type: 0 | 1
  expression?: string
  refParams?: string
  xaxisPoints?: string
  yaxisPoints?: string
  allowExtrapolation?: boolean | number
}

interface ParameterWithChildren extends Parameter {
  children?: ParameterWithChildren[]
}

const props = defineProps<{
  parameters: ParameterWithChildren[]
  selectedVirtualParams?: any[]
}>()

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'drawVirtualParam', value: any): void
}>()

// 拖动相关状态
const position = ref({ x: 100, y: 100 })
const isDragging = ref(false)
const dragStart = ref({ x: 0, y: 0 })
const initialPosition = ref({ x: 0, y: 0 })

// 获取当前窗口实际尺寸
const getDialogSize = () => {
  const screenWidth = window.innerWidth
  const screenHeight = window.innerHeight
  
  // 根据媒体查询判断当前应该使用的尺寸
  if (screenWidth <= 1024) {
    return {
      width: Math.min(screenWidth * 0.35, 700), // 50vw，最大700px
      height: Math.min(screenHeight * 0.90, 600) // 85vh，最大600px
    }
  } else {
    return {
      width: screenWidth * 0.35, // 35%
      height: screenHeight * 0.90  // 80%
    }
  }
}

// 拖动功能
const startDrag = (event: MouseEvent) => {
  if (event.target === event.currentTarget || (event.target as Element).tagName === 'H2') {
    isDragging.value = true
    dragStart.value = { x: event.clientX, y: event.clientY }
    initialPosition.value = { x: position.value.x, y: position.value.y }
    document.addEventListener('mousemove', handleDrag)
    document.addEventListener('mouseup', stopDrag)
    event.preventDefault()
  }
}

const handleDrag = (event: MouseEvent) => {
  if (!isDragging.value) return
  
  const deltaX = event.clientX - dragStart.value.x
  const deltaY = event.clientY - dragStart.value.y
  
  const dialogSize = getDialogSize()
  
  position.value = {
    x: Math.max(0, Math.min(window.innerWidth - dialogSize.width, initialPosition.value.x + deltaX)),
    y: Math.max(0, Math.min(window.innerHeight - dialogSize.height, initialPosition.value.y + deltaY))
  }
}

const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
}

// 窗口大小变化时调整位置，确保窗口不会超出屏幕
const handleResize = () => {
  const dialogSize = getDialogSize()
  position.value = {
    x: Math.max(0, Math.min(window.innerWidth - dialogSize.width, position.value.x)),
    y: Math.max(0, Math.min(window.innerHeight - dialogSize.height, position.value.y))
  }
}

// 组件挂载时设置初始位置为居中
onMounted(async () => {
  const dialogSize = getDialogSize()
  position.value = {
    x: Math.max(0, (window.innerWidth - dialogSize.width) / 2),
    y: Math.max(0, (window.innerHeight - dialogSize.height) / 2)
  }

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
  await queryVirtualParamsList()

  // 根据传入的已选虚拟参数同步复选框状态
  if (props.selectedVirtualParams && props.selectedVirtualParams.length > 0) {
    selectedParams.value = props.selectedVirtualParams.map(param => param.name)
    // 去掉最前面的V_
    selectedParams.value = selectedParams.value.map(param => param.replace(/^V_/, ''))
    // 判断是否在当前的虚拟参数列表
    selectedParams.value = selectedParams.value.filter(param => virtualParameters.value.some(vp => vp.name === param))
  }
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
  window.removeEventListener('resize', handleResize)
})

// 状态管理
const activeTab = ref<'formula' | 'calibration'>('formula')
const virtualParameters = ref<VirtualParameter[]>([])

// 搜索相关
const searchQuery = ref('')

// 自建公式相关
const formulaExpression = ref('') // 公式
const formulaName = ref('') //虚拟参数名称

// 标定线转换相关
const calibrationParamName = ref('') //标定转换选择参数名称
const xCalibrationPoints = ref('') //x轴标定点
const yCalibrationPoints = ref('') // y轴标定点
const allowExtrapolation = ref(false) //是否允许外插
const virtualName = ref('') // 虚拟参数名称
const calibrationParamId = ref('') //标定转换选择参数id 逗号分隔
const calibrationParamIdList = ref<string[]>([]) //标定转换选择参数id列表

// 编辑状态
const editingParam = ref<VirtualParameter | null>(null)

// 选中的参数列表
const selectedParams = ref<string[]>([])

// Loading状态管理
const isLoading = ref(false)

// 计算属性：扁平化参数列表（只显示连续量，支持搜索过滤）
const flatParameters = computed(() => {
  const flatten = (params: ParameterWithChildren[]): ParameterWithChildren[] => {
    const result: ParameterWithChildren[] = []
    for (const param of params) {
      // 只添加连续量参数
      if (isContinuousParameter(param)) {
        result.push(param)
      }
      if (param.children) {
        result.push(...flatten(param.children))
      }
    }
    return result
  }
  
  let allParams = flatten(props.parameters || [])
  
  // 如果有搜索关键词，进行过滤
  if (searchQuery.value) {
    const searchTerm = searchQuery.value.toLowerCase()
    allParams = allParams.filter(param => 
      param.name.toLowerCase().includes(searchTerm)
    )
  }
  
  return allParams
})

// 判断参数是否为连续量
const isContinuousParameter = (param: ParameterWithChildren): boolean => {
  // 通过mode判断：mode为0表示连续量，mode为1表示离散量
  if (param.mode === 0) return true
  if (param.mode === 1) return false
  
  // 默认情况下，如果都没有明确标识，则视为连续量
  return true
}

// 添加参数到公式或选择为标定参数
const addParamToFormula = (param: ParameterWithChildren) => {
  if (activeTab.value === 'formula') {
    // 自建公式标签页：添加到公式表达式
    formulaExpression.value += `[${param.name}]`
    // 去重
    calibrationParamIdList.value.push(param.name)
    calibrationParamIdList.value = [...new Set(calibrationParamIdList.value)]
  } else if (activeTab.value === 'calibration') {
    // 标定线转换标签页：选择为标定参数
    calibrationParamName.value = param.name
    calibrationParamId.value = param.name
    calibrationParamIdList.value = [param.name]
  }
}

// 添加内容到公式
const addToFormula = (value: string) => {
  if (formulaExpression.value == '公式') {
    formulaExpression.value = ''
  }
  formulaExpression.value += value
}

// 清空公式
const clearFormula = () => {
  formulaExpression.value = ''
  calibrationParamIdList.value = []
}

// 回退一格
const backspaceFormula = () => {
  const currentExpression = formulaExpression.value
  if (currentExpression.length === 0) return
  
  const lastChar = currentExpression[currentExpression.length - 1]
  
  // 如果删除的是参数结束符']'
  if (lastChar === ']') {
    // 找到最后一个参数的起始位置
    const lastBracketIndex = currentExpression.lastIndexOf('[')
    if (lastBracketIndex !== -1) {
      // 提取参数名称
      const paramName = currentExpression.substring(lastBracketIndex + 1, currentExpression.length - 1)
      
      // 找到对应的参数ID并从列表中移除
      const paramToRemove = flatParameters.value.find(param => param.name === paramName)
      if (paramToRemove) {
        const paramIdString = String(paramToRemove.id)
        const paramIdIndex = calibrationParamIdList.value.indexOf(paramIdString)
        if (paramIdIndex !== -1) {
          calibrationParamIdList.value.splice(paramIdIndex, 1)
        }
      }
      
      // 删除整个参数表达式 [参数名]
      formulaExpression.value = currentExpression.substring(0, lastBracketIndex)
      // 在calibrationParamIdList中删除对应的参数id
      calibrationParamIdList.value = calibrationParamIdList.value.filter(id => id !== paramName)
    } else {
      // 如果没有找到对应的'['，只删除']'
      formulaExpression.value = currentExpression.slice(0, -1)
    }
  } else {
    // 普通删除
    formulaExpression.value = currentExpression.slice(0, -1)
  }
}

// 保存自建公式
const saveFormula = async () => {
  if (!formulaName.value || !formulaExpression.value) return
  
  let virtualParam = {}
  isLoading.value = true
  calibrationParamId.value = calibrationParamIdList.value.join(',')
  try {
    if (editingParam.value) {
      // 编辑模式
      virtualParam = {
        ...editingParam.value,
        type: 0,
        name: formulaName.value,
        expression: formulaExpression.value,
        refParams: calibrationParamId.value,
      }
      const res: any = await API.updateVirtualParam(virtualParam)
      if (res && res.code === 200) {
        messageRef.value?.show({
          type: 'success',
          content: '编辑虚拟参数成功',
          duration: 3000
        })
        queryVirtualParamsList()
        // 移除选中列表中编辑前的参数
        if (editingParam.value && editingParam.value.name && selectedParams.value.includes(editingParam.value.name)) {
          selectedParams.value = selectedParams.value.filter(name => name !== editingParam.value.name)
        }
        // 退出编辑模式并清空表单
        exitEditMode()
      }
    } else {
      // 新建模式 - 创建新参数
      virtualParam = {
        type: 0,
        name: formulaName.value,
        expression: formulaExpression.value,
        refParams: calibrationParamId.value,
      }
      const res: any = await API.addVirtualParam(virtualParam)
      if (res && res.code === 200) {
        messageRef.value?.show({
          type: 'success',
          content: '新增虚拟参数成功',
          duration: 3000
        })
        queryVirtualParamsList()
        // 清空表单
        exitEditMode()
      }
    }
  } catch (error: any) {
    // 尝试从错误响应中获取错误消息
    let errorMessage = '保存虚拟参数失败'
    if (error.response && error.response.data && error.response.data.msg) {
      errorMessage = error.response.data.msg
    } else if (error.message) {
      errorMessage = error.message
    }
    
    messageRef.value?.show({
      type: 'error',
      content: errorMessage,
      duration: 3000
    })
  } finally {
    isLoading.value = false
  }
}

// 保存标定线转换
const saveCalibration = async () => {
  if (!virtualName.value || !calibrationParamName.value || !xCalibrationPoints.value || !yCalibrationPoints.value) return
  
  // const xPoints = xCalibrationPoints.value.split(',').map(x => parseFloat(x.trim())).filter(x => !isNaN(x))
  // const yPoints = yCalibrationPoints.value.split(',').map(y => parseFloat(y.trim())).filter(y => !isNaN(y))
  
  // if (xPoints.length !== yPoints.length) {
  //   alert('X轴和Y轴标定点数量必须相等')
  //   return
  // }
  
  let virtualParam = {}
  isLoading.value = true
  calibrationParamId.value = calibrationParamIdList.value.join(',')
  try {
    if (editingParam.value) {
      // 编辑模式
      virtualParam = {
        ...editingParam.value,
        name: virtualName.value,
        type: 1,
        refParams: calibrationParamId.value,
        xaxisPoints: xCalibrationPoints.value,
        yaxisPoints: yCalibrationPoints.value,
        allowExtrapolation: allowExtrapolation.value,
      }
      const res: any = await API.updateVirtualParam(virtualParam)
      if (res && res.code === 200) {
        messageRef.value?.show({
          type: 'success',
          content: '编辑虚拟参数成功',
          duration: 3000
        })
        queryVirtualParamsList()
        // 移除选中列表中编辑前的参数
        if (editingParam.value && editingParam.value.name && selectedParams.value.includes(editingParam.value.name)) {
          selectedParams.value = selectedParams.value.filter(name => name !== editingParam.value.name)
        }
        // 退出编辑模式并清空表单
        exitEditMode()
      }
    } else {
      // 新建模式
      virtualParam = {
        name: virtualName.value,
        type: 1,
        refParams: calibrationParamId.value,
        xaxisPoints: xCalibrationPoints.value,
        yaxisPoints: yCalibrationPoints.value,
        allowExtrapolation: allowExtrapolation.value,
      }
      const res: any = await API.addVirtualParam(virtualParam)
      if (res && res.code === 200) {
        messageRef.value?.show({
          type: 'success',
          content: '新增虚拟参数成功',
          duration: 3000
        })
        queryVirtualParamsList()
        // 清空表单
        exitEditMode()
      }
    }
  } catch (error: any) {
    // 尝试从错误响应中获取错误消息
    let errorMessage = '保存虚拟参数失败'
    if (error.response && error.response.data && error.response.data.msg) {
      errorMessage = error.response.data.msg
    } else if (error.message) {
      errorMessage = error.message
    }
    
    messageRef.value?.show({
      type: 'error',
      content: errorMessage,
      duration: 3000
    })
  } finally {
    isLoading.value = false
  }
}

// 编辑虚拟参数
const editVirtualParam = (param: VirtualParameter) => {
  // 如果当前正在编辑这个参数，则退出编辑模式
  if (editingParam.value && editingParam.value.id === param.id) {
    exitEditMode()
    return
  }
  
  // 否则进入编辑模式
  editingParam.value = param
  
  if (param.type == 0) {
    activeTab.value = 'formula'
    formulaName.value = param.name
    formulaExpression.value = param.expression || ''
    calibrationParamIdList.value = param.refParams ? param.refParams.split(',') : []
  } else {
    activeTab.value = 'calibration'
    virtualName.value = param.name
    // 根据refParams找到对应的参数名称
    // const selectedParam = flatParameters.value.find(p => p.name == param.refParams)
    // calibrationParamName.value = selectedParam ? selectedParam.name : ''
    // calibrationParamId.value = selectedParam ? selectedParam.name : ''
    // calibrationParamIdList.value = selectedParam ? [selectedParam.name] : []
    calibrationParamName.value = param.refParams || ''
    calibrationParamId.value = param.refParams || ''
    calibrationParamIdList.value = param.refParams ? [param.refParams] : []
    xCalibrationPoints.value = param.xaxisPoints || ''
    yCalibrationPoints.value = param.yaxisPoints || ''
    allowExtrapolation.value = param.allowExtrapolation === 1 || param.allowExtrapolation === true
  }
}

// 退出编辑模式
const exitEditMode = () => {
  editingParam.value = null
  
  // 清空表单数据
  formulaName.value = ''
  formulaExpression.value = ''
  virtualName.value = ''
  calibrationParamName.value = ''
  calibrationParamId.value = ''
  calibrationParamIdList.value = []
  xCalibrationPoints.value = ''
  yCalibrationPoints.value = ''
  allowExtrapolation.value = false
}

// 删除虚拟参数
const deleteVirtualParam = async (param: VirtualParameter) => {
  if (confirm(`确定要删除虚拟参数"${param.name}"吗？`)) {
    isLoading.value = true
    try {
      // 虚拟参数有id
      const res: any = await API.removeVirtualParam(param.id)
      if (res && res.code === 200) {
        messageRef.value?.show({
          type: 'success',
          content: '删除虚拟参数成功',
          duration: 3000
        })
        
        // 如果被删除的参数在选中列表中，移除它
        if (param.name && selectedParams.value.includes(param.name)) {
          selectedParams.value = selectedParams.value.filter(name => name !== param.name)
          // 去掉最前面的V_
          selectedParams.value = selectedParams.value.map(param => param.replace(/^V_/, ''))
        }
        // 如果正在编辑被删除的参数，退出编辑模式
        if (editingParam.value && editingParam.value.id === param.id) {
          exitEditMode()
        }
        const selectedVirtualParams = virtualParameters.value.filter(param =>
          param.name && selectedParams.value.includes(param.name)
        ).map(param => ({
          ...param,
          name: 'V_' + param.name
        }))
        // 重新绘图
        emit("drawVirtualParam", selectedVirtualParams)
        // 刷新列表
        queryVirtualParamsList()
      }
    } catch (error: any) {
      // 尝试从错误响应中获取错误消息
      let errorMessage = '删除虚拟参数失败'
      if (error.response && error.response.data && error.response.data.msg) {
        errorMessage = error.response.data.msg
      } else if (error.message) {
        errorMessage = error.message
      }
      
      messageRef.value?.show({
        type: 'error',
        content: errorMessage,
        duration: 3000
      })
    } finally {
      isLoading.value = false
    }
  }
}

// 绘制选中的参数
const drawSelectedParams = () => {
  // 找到选中的虚拟参数（即使没有选中任何参数，也要通知父组件当前状态）
  // 为每个虚拟参数名称添加"V_"前缀
  // TODO
  const selectedVirtualParams = virtualParameters.value.filter(param =>
    param.name && selectedParams.value.includes(param.name)
  ).map(param => ({
    ...param,
    name: 'V_' + param.name
  }))
  
  // 批量绘制 - 传递当前选中的虚拟参数列表
  emit("drawVirtualParam", selectedVirtualParams)
}

// 查询已创建虚拟参数列表
const queryVirtualParamsList = async () => {
  isLoading.value = true
  
  try {
    const res: any = await API.queryVirtualList()
    if (res && res.code === 200) {
      virtualParameters.value = res.data || []
    }
  } catch (error: any) {
    // 尝试从错误响应中获取错误消息
    let errorMessage = '查询虚拟参数列表失败'
    if (error.response && error.response.data && error.response.data.msg) {
      errorMessage = error.response.data.msg
    } else if (error.message) {
      errorMessage = error.message
    }
    
    messageRef.value?.show({
      type: 'error',
      content: errorMessage,
      duration: 3000
    })
  } finally {
    isLoading.value = false
  }
}

// 处理X轴标定点输入，自动转换中文逗号为英文逗号
const handleXCalibrationInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target && target.value) {
    const convertedValue = target.value.replace(/，/g, ',')
    xCalibrationPoints.value = convertedValue
  }
}

// 处理Y轴标定点输入，自动转换中文逗号为英文逗号
const handleYCalibrationInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target && target.value) {
    const convertedValue = target.value.replace(/，/g, ',')
    yCalibrationPoints.value = convertedValue
  }
}

// 添加一个watch监听器，当props.selectedVirtualParams发生变化时同步更新selectedParams状态
watch(() => props.selectedVirtualParams, (newValue) => {
  if (newValue) {
    selectedParams.value = newValue.map(param => param.name)
    // 去掉最前面的V_
    selectedParams.value = selectedParams.value.map(param => param.replace(/^V_/, ''))
  } else {
    selectedParams.value = []
  }
})

const clearSelectedParams = () => {
  selectedParams.value = []
}

defineExpose({
  clearSelectedParams
})
</script>

<style scoped>
@import '../../../src/assets/css/theme.css';
@import '../../../src/assets/css/buttons.css';
@import '../../../src/assets/css/modal.css';
*{ 
  -webkit-touch-callout:none; /*系统默认菜单被禁用*/
  -webkit-user-select:none; /*webkit浏览器*/
  -khtml-user-select:none; /*早期浏览器*/
  -moz-user-select:none;/*火狐*/
  -ms-user-select:none; /*IE10*/
  user-select:none; 
}
.virtual-param-dialog {
  position: fixed;
  width: 35%;
  height: 90%;
  backdrop-filter: blur(10px);
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index: 9999;
  animation: modalAppear 0.3s ease-out;
  /*border: 1px solid var(--modal-divide);*/
}
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1100;
    overflow: hidden !important;
}
@keyframes modalAppear {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.virtual-param-dialog::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  /*background: linear-gradient(90deg,*/
  /*  rgba(56, 189, 248, 0.5) 0%,*/
  /*  rgba(30, 64, 175, 0.8) 50%,*/
  /*  rgba(56, 189, 248, 0.5) 100%);*/
  z-index: 3;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid var(--modal-divide);
  position: relative;
  z-index: 2;
  user-select: none;
  transition: background-color 0.2s ease;
}

.dialog-header h2 {
  margin: 0;
  color: var(--text-color);
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    color: var(--text-color);
    font-size: 20px;
    font-weight: 700;
    transition: color 0.2s;
}

.close-btn:hover {
    color: rgba(0, 0, 0, 0.85);
}

.dialog-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.left-panel {
  width: 200px;
  border-right: 1px solid var(--modal-divide);
  backdrop-filter: blur(5px);
  display: flex;
  flex-direction: column;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.panel-title {
  margin: 0;
  padding: 12px 12px 0 12px;
  font-size: 16px;
  font-weight: 600;
    color: var(--text-color);
  background: var(--se-sub-plate-bg-color);
}

/* 文件选择器样式 */
.file-selector {
  padding: 12px 12px 0 12px;
}

.file-label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  font-weight: 500;
    color: var(--text-color);
}

.tech-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid rgba(30, 64, 175, 0.2);
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.9);
    color: var(--text-color);
  font-size: 14px;
  transition: all 0.2s ease;
}

.tech-select:focus {
  outline: none;
  border-color: rgba(59, 130, 246, 0.5);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.tech-select:hover {
  border-color: rgba(59, 130, 246, 0.4);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .file-selector {
    margin-bottom: 8px;
  }
  
  .file-label {
    font-size: 12px;
    margin-bottom: 4px;
  }
  
  .tech-select {
    padding: 6px 10px;
    font-size: 12px;
  }
}


.search-box {
  padding: 8px 12px;
  border-bottom: 1px solid var(--modal-divide);
    background: var(--se-sub-plate-bg-color);
}

.tech-input {
  width: 100%;
  padding: 8px 12px;
  font-size: 14px;
  border-radius: 4px;
    background: var(--select-background);
    color: var(--text-color);
    border: 1px solid var(--input-border-color);
  transition: all 0.2s ease;
}

.tech-input:focus {
  outline: none;
  border-color: rgba(30, 64, 175, 0.4);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}
.tech-input::placeholder {
  color: var(--preview-text-color);
}
.param-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
    color: var(--text-color);
    background: var(--se-main-bg-color);
}

.param-item {
    color: var(--text-color);
    background: var(--se-main-bg-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.param-item:hover {
    color: var(--se-main-bg-color);
    background: var(--text-color);
}

.param-name {
  font-weight: 400;
  font-size: 14px;
  word-break: break-all;
}

.param-name-table {
  font-weight: 400;
  color: var(--text-color);
  font-size: 14px;
  word-break: break-all;
  text-align: center;
}

.virtual-param-list {
  height: 35%;
  border-bottom: 1px solid rgba(30, 64, 175, 0.1);
  display: flex;
  flex-direction: column;
}

.param-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--modal-divide);
    background: var(--se-sub-plate-bg-color);
}

.param-list-header .panel-title {
  border-bottom: none;
  background: none;
  margin: 0;
  flex: 1;
}

.batch-actions {
  padding: 12px 16px;
}

.checkbox-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.param-checkbox {
    border: 1px solid var(--btn-click-color);
    background-color: var(--ant-checkbox-inner);
    color: var(--global-color-white);
    appearance: none;
    -webkit-appearance: none;
    width: 16px !important;
    height: 16px !important;
    border-radius: 4px; /* 圆角 */
    outline: none;
    cursor: pointer;
    position: relative;
    transition: all 0.2s ease; /* 平滑过渡效果 */
}
.param-checkbox:checked{
    color: var(--global-color-white);
    background-color: var(--ant-checkbox-checked);
    border-color: var(--btn-click-color);
}
.param-checkbox:checked::after{
    content: "";
    position: absolute;
    left: 30%;
    top: 1px;
    width: 6px;
    height: 10px;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
}

.virtual-table {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 40px 100px 1fr 90px;
  padding: 10px 14px 10px 14px;
  /*margin-right: 8px; !* 为滚动条预留空间 *!*/
  background: var(--table-body-bg-color);
  border-bottom: 1px solid var(--table-solid);
  font-weight: 600;
  color: var(--text-color);
  position: sticky;
  top: 0;
  z-index: 10;
  justify-items: center;
  text-align: center;
}

.table-body {
  flex: 1;
  overflow-y: auto;
  scrollbar-gutter: stable; /* 为现代浏览器提供稳定的滚动条空间 */
}

.table-row {
  display: grid;
  grid-template-columns: 40px 100px 1fr 90px;
  padding: 10px 14px;
  border-bottom: 1px solid var(--table-solid);
  align-items: center;
  justify-items: center;
  text-align: center;
  transition: background-color 0.2s;

}

.table-row:hover {
  background: rgba(30, 64, 175, 0.03);
}

.param-type-badge {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  font-weight: 500;
  display: inline-block;
  width: fit-content;
    background: var(--table-body-bg-color);
    color: var(--text-color);
}

.param-type-badge_formula {
  background: var(--table-body-bg-color);
  color: var(--text-color);
}

.param-type-badge_calibration {
    background: var(--table-body-bg-color);
    color: var(--text-color);
}

.actions {
  display: flex;
  gap: 6px;
  justify-content: center;
}

.action-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.edit-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tab-header {
  display: flex;
  border-bottom: 1px solid rgba(30, 64, 175, 0.1);
    background: var(--se-sub-plate-bg-color);
}

.tab-btn {
  padding: 12px 24px;
  border: none;
  background: none;
  cursor: pointer;
  font-weight: 600;
    background: var(--btn-color);
    color: var(--text-color);
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.tab-btn.active {
    background: var(--btn-click-color);
    color: var(--text-color);
  /*border-bottom-color: #1e3a8a;*/
}

.tab-btn:hover:not(.active) {
  background: rgba(30, 64, 175, 0.03);
    color: var(--text-color);
}

.formula-tab,
.calibration-tab {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.formula-display {
  margin-bottom: 12px;
}

.formula-input {
  width: 100%;
  min-height: 50px;
  padding: 12px;
    background: var(--select-background);
    color: var(--text-color);
    border: 1px solid var(--input-border-color);
  border-radius: 6px;
  /* font-family: monospace; */
  margin-bottom: 12px;
  word-break: break-all;
}

.formula-note {
  color: var(--error-color);
  font-size: 12px;
  margin-bottom: 12px;
}

.calculator {
  display: grid;
  gap: 4px;
  /* max-width: 480px; */
  width: 100%;
}

.calc-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
}

.calc-btn {
  padding: 6px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.calc-btn:hover {
  background: #f3f4f6 !important;;
}

.calc-btn.operator {
  background: #3b82f6 !important;;
  border-color: #3b82f6 !important;;
}

.calc-btn.operator:hover {
  background: #2563eb !important;;
}

.calc-btn.function {
  background: #10b981 !important;
  border-color: #10b981 !important;;
}

.calc-btn.function:hover {
  background: #059669 !important;;
}

.calc-btn-wide {
  grid-column: span 3;
}

.formula-name {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-top: 20px;
}

.formula-name .save-btn {
  margin-left: auto;
}
.formula-name label {
  font-weight: 500;
  color: #374151;
}

.calibration-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  font-weight: 500;
    color: var(--text-color);
}

.tech-checkbox {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    position: relative;
    flex: 1;
}

.tech-checkbox input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
    height: 0;
    width: 0;
}

.checkbox-custom {
    position: relative;
    height: 18px;
    width: 18px;
    min-width: 18px;
    border-radius: 4px;
    border: 1px solid var(--btn-click-color);
    background-color: var(--ant-checkbox-inner);
    color: var(--global-color-white);
}

.tech-checkbox input:checked ~ .checkbox-custom {
    color: var(--global-color-white);
    background-color: var(--ant-checkbox-checked);
    border-color: var(--btn-click-color);
}

.checkbox-custom:after {
    content: "";
    position: absolute;
    display: none;
    left: 6px;
    top: 2px;
    width: 5px;
    height: 10px;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
}

.tech-checkbox input:checked ~ .checkbox-custom:after {
    display: block;
}

.form-checkbox {
  width: 16px;
  height: 16px;
}

.param-select,
.calibration-input,
.name-input {
  padding: 8px 12px;
    background: var(--select-background);
    color: var(--text-color);
    border: 1px solid var(--input-border-color);
  border-radius: 6px;
  font-size: 14px;
}

.param-select:focus,
.calibration-input:focus,
.name-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.save-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  align-self: flex-end;
}


/* 1024*768分辨率适配 */
@media (max-width: 1024px) {
  .virtual-param-dialog {
    width: 55vw;
    height: 85vh;
    max-width: 700px;
    max-height: 600px;
  }
  .dialog-header {
    padding: 10px 12px;
  }
  .dialog-header h2{
    font-size: 15px;
  }
  .left-panel {
    width: 150px;
  }
  
  .panel-title {
    padding: 8px;
    font-size: 14px;
  }
  
  .param-item {
    padding: 6px 8px;
  }
  
  .param-name {
    font-size: 11px;
  }

  .param-name-table {
    font-size: 11px;
  }
  
  .search-box {
    padding: 8px 12px;
  }

  .tab-btn {
    font-size: 14px;
    padding: 6px 14px;
  }
  
  .tech-input {
    padding: 6px 8px;
    font-size: 12px;
  }
  
  .table-header {
    grid-template-columns: 40px 80px 1fr 90px;
    padding: 6px 10px;
    margin-right: 6px; /* 小屏幕下为滚动条预留较小空间 */
    font-size: 12px;
  }
  
  .table-row {
    grid-template-columns: 40px 80px 1fr 90px;
    padding: 6px 10px;
  }

  .param-type-badge {
    font-size: 11px;
  }

  .action-btn {
    font-size: 11px;
    padding: 3px 5px;
  }

  .param-checkbox {
    height: 16px;
    width: 16px;
  }
  
  .table-body {
    flex: 1;
    overflow-y: auto;
  }
  .formula-tab,
  .calibration-tab {
    padding: 12px;
  }
  .calc-btn {
    padding: 4px;
    font-size: 12px;
  }
  
  .formula-input {
    min-height: 32px;
    padding: 6px;
    font-size: 12px;
  }

  .formula-note {
    font-size: 10px;
    margin-bottom: 8px;
  }
  
  .param-select,
  .calibration-input,
  .name-input {
    padding: 6px 8px;
    font-size: 12px;
  }

  .form-group label {
    font-size: 12px;
  }
  .save-btn {
    padding: 4px 8px;
    font-size: 12px;
  }

  .batch-actions {
    padding: 8px 12px;
  }

  .batch-draw-btn {
    padding: 4px 8px;
    font-size: 11px;
  }
}

/* Loading样式 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: var(--loading-bg-color);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  border-radius: 12px;
}

.spinner {
  border: 5px solid #fcfcfc;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

</style>